<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class session_file implements session_interface {

	protected $save_path = '';

	public function __construct($save_path) {

		$path = (!empty($save_path)) ? $save_path : rtrim(BASEPATH, '/') .'/.sessions';
		
		$this->save_path = rtrim($path, '/') . '/';

	}

	public function read($id) {
		$filename = $this->filename($id);

		if(file_exists($filename)) {
			$fp = fopen($filename, 'r');

			if($fp) {

				$data = '';

				while(!feof($fp)) {
					$data .= fread($fp, 128);
				}
				
				fclose($fp);

				// it returns false on fail
				return $this->unserialize($data);
			}
		}

		return false;
	}

	public function write($data) {
		$filename = $this->filename($data['session_id']);

		$fp = fopen($filename, 'w');

		if($fp) {
			$serialized = $this->serialize($data);
			fwrite($fp, $serialized);
			fclose($fp);

			return true;
		}

		return false;
	}

	public function create($data) {
		return $this->write($data);
	}

	public function destroy($id) {
		$filename = $this->filename($id);
		if(file_exists($filename)) {
			return @unlink($filename);
		}

		return false;
	}

	public function gc($expire) {
		return 0;
	}

	protected function serialize($data) {
		return serialize($data);
	}

	protected function unserialize($data) {
		return unserialize($data);
	}

	protected function filename($id) {
		return $this->save_path . $id;
	}

}
